using System;

namespace Ro.Norc.ServiceStackClient
{
	public abstract class ServiceEncoderBase : ServiceEncoderInterface
	{
		/// <summary>
		/// An array containing the content types the current encoder instance accepts as valid
		/// </summary>
		protected string[] _allowedTypes = null;
		
		/// <summary>
		/// The content type of the string representation produced by ServiceEncoderInterface.Encode()
		/// </summary>
		protected string _contentType = null;
		
		/// <summary>
		/// The string that is automatically appended to the URL by the Service class, should this behaviour be enabled
		/// </summary>
		protected string _endpointPart = null;
		
		/// <summary>
		/// Encodes a given object to a string representation
		/// </summary>
		/// <param name="obj">
		/// The object to encode
		/// </param>
		/// <returns>
		/// The resulting string representation or null if the given reference is null
		/// </returns>
		public abstract string Encode(object obj);
		
		/// <summary>
		/// Decodes a given string representation to an object of the given type parameter T
		/// </summary>
		/// <param name="repr">
		/// The string representation of the object that should be decoded
		/// </param>
		/// <param name="t">
		/// The type to be deserialized to
		/// </param>
		/// <returns>
		/// The resulting deserialized object
		/// </returns>
		public abstract object Decode(string repr, Type t);
		
		/// <summary>
		/// Returns true if the encoder can decode string representations of the given content type. This method is called before attempting a decode operation.
		/// </summary>
		/// <param name="contentType">
		/// The content type to be validated
		/// </param>
		/// <returns>
		/// True if the encoder supports the given content type, false otherwise
		/// </returns>
		public virtual bool IsContentTypeValid(string contentType) 
		{
			if (string.IsNullOrEmpty(contentType)) {
				return false;
			}
			if (_allowedTypes == null || _allowedTypes.Length == 0) {
				return true;
			}
			contentType = contentType.ToLower();
			
			foreach (string mimeType in _allowedTypes) {
				if (mimeType == contentType) {
					return true;
				}
			}
			return false;
		}
		
		/// <summary>
		/// Gets the content type of the string representation produced by ServiceEncoderInterface.Encode()
		/// </summary>
		public virtual string ContentType
		{
			get {
				return _contentType;
			}
		}
		
		/// <summary>
		/// Gets the string that is automatically appended to the URL by the Service class, should this behaviour be enabled
		/// </summary>
		public virtual string EndpointPart
		{
			get {
				return _endpointPart;
			}
		}
	}
}